package com.logic.meeting.app.main;

import android.Manifest;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatImageView;
import androidx.appcompat.widget.AppCompatTextView;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.logic.meeting.app.R;
import com.logic.meeting.app.R2;
import com.logic.meeting.app.entity.MeetingHomeListEntity;
import com.logic.meeting.app.event.HomeHeartBeatEvent;
import com.logic.meeting.app.fusion.FusionCode;
import com.logic.meeting.app.fusion.FusionPre;
import com.logic.meeting.app.fusion.FusionTag;
import com.logic.meeting.app.main.adapter.IndexMeetingListAdapter;
import com.logic.meeting.app.util.DownloadUtil;
import com.logic.meeting.app.util.LekUtil;
import com.logic.meeting.app.util.OpenUDID;
import com.logic.meeting.core.delegates.AtmosDelegate;
import com.logic.meeting.core.net.HttpHelper;
import com.logic.meeting.core.net.HttpUrl;
import com.logic.meeting.core.net.callback.IError;
import com.logic.meeting.core.net.callback.IFailure;
import com.logic.meeting.core.net.callback.ISuccess;
import com.logic.meeting.core.util.StringUtil;
import com.logic.meeting.core.util.storage.AtmosPreference;
import com.smbd.peripheral.SmbdLed;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.OnLongClick;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;

public class IndexMachineHomeDelegate extends AtmosDelegate {
    private int clickNum = 0;
    private IndexMeetingListAdapter mAdapter;
    private SimpleDateFormat format;
    private SmbdLed mSmbdLed;
    private List<MeetingHomeListEntity.DataBean.ListBean> mMeetingList;

    @BindView(R2.id.rlv_meeting_list)
    RecyclerView rlvMeetingList;
    @BindView(R2.id.tv_week_day)
    AppCompatTextView tvWeekDay;
    @BindView(R2.id.tv_date)
    AppCompatTextView tvDate;
    @BindView(R2.id.tv_meeting_room)
    AppCompatTextView tvMeetingRoom;
    @BindView(R2.id.tv_meeting_status)
    AppCompatTextView tvMeetingStatus;
    @BindView(R2.id.iv_meeting_time)
    AppCompatImageView ivMeetingTime;
    @BindView(R2.id.tv_meeting_time)
    AppCompatTextView tvMeetingTime;
    @BindView(R2.id.iv_meeting_company)
    AppCompatImageView ivMeetingCompany;
    @BindView(R2.id.tv_meeting_company)
    AppCompatTextView tvMeetingCompany;
    @BindView(R2.id.cl_right_center)
    ConstraintLayout clRightCenter;
    @BindView(R2.id.iv_qr_code)
    AppCompatImageView ivQrCode;

    @OnClick(R2.id.tv_close_app)
    void onGoBack() {
        if (clickNum < 4) {
            clickNum += 1;
        } else {
            getSupportDelegate().start(new IndexSettingPageDelegate());
            clickNum = 0;
        }
    }


    @Override
    public Object setLayout() {
        return R.layout.delegate_home;
    }

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, View rootView) {
//        mSmbdLed = new SmbdLed();
        tvMeetingRoom.setText(AtmosPreference.getCustomStringPre(FusionPre.MEETING_ROOM));
        initRecycler();
        initTimeData();
        initData();
    }

    @SuppressLint("SimpleDateFormat")
    private void initData() {

        JSONObject params = new JSONObject();
        params.put("deviceId", OpenUDID.getOpenUDID());
        params.put("meetingDate", new SimpleDateFormat("yyyy-MM-dd").format(new Date(System.currentTimeMillis())));

        HttpHelper.RestClientPostRaw(params, HttpUrl.MEETING_LIST,
                new ISuccess() {
                    @Override
                    public void onSuccess(String response) {
                        Type type = new TypeToken<MeetingHomeListEntity>() {
                        }.getType();
                        Gson gson = new Gson();
                        MeetingHomeListEntity mData = gson.fromJson(response, type);
                        if (mData.getStatus().equals(FusionCode.SUCCESS)) {
                            if (mData.getData().getList() != null && mData.getData().getList().size() > 0) {
                                mMeetingList = mData.getData().getList();
                                mAdapter.setmData(mMeetingList);
                                mAdapter.notifyDataSetChanged();
                                if (mMeetingList.get(0).getStatus().equals("1")) {
                                    setUseNow(mMeetingList.get(0), "会议中");
                                    LekUtil.setLekLight(getContext(), FusionTag.RED_LIGHT);
                                } else if (mMeetingList.get(0).getStatus().equals("0")) {
                                    setUseNow(mMeetingList.get(0), "待开始");
                                    LekUtil.setLekLight(getContext(), FusionTag.BLUE_LIGHT);
                                } else if (mMeetingList.get(0).getStatus().equals("2")) {
                                    setUseNow(mMeetingList.get(0), "已结束");
                                    LekUtil.setLekLight(getContext(), FusionTag.GREEN_LIGHT);
                                } else if (mMeetingList.get(0).getStatus().equals("3")) {
                                    setUseNow(mMeetingList.get(0), "已取消");
                                    LekUtil.setLekLight(getContext(), FusionTag.GREEN_LIGHT);
                                }
                            } else {
                                mMeetingList = new ArrayList<>();
                                mAdapter.setmData(mMeetingList);
                                mAdapter.notifyDataSetChanged();
                                setUnUse();
                            }
                            Glide.with(getContext()).load(mData.getData().getQrCodeUrl()).into(ivQrCode);
                        }
                    }
                }, new IError() {
                    @Override
                    public void onError(int code, String msg) {

                    }
                }, new IFailure() {
                    @Override
                    public void onFailure() {

                    }
                });

    }

    private void setUnUse() {
        LekUtil.setLekLight(getContext(), FusionTag.GREEN_LIGHT);
        ivMeetingTime.setVisibility(View.GONE);
        ivMeetingCompany.setVisibility(View.GONE);
        tvMeetingTime.setVisibility(View.GONE);
        tvMeetingCompany.setVisibility(View.GONE);
        tvMeetingStatus.setText("暂无会议");
        clRightCenter.setBackgroundColor(getResources().getColor(R.color.un_use));
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    mSmbdLed.onGreen(true);
                } catch (Exception e) {

                }
            }
        }).start();
    }

    @SuppressLint("SetTextI18n")
    private void setUseNow(MeetingHomeListEntity.DataBean.ListBean data, String tips) {
        tvMeetingTime.setText(StringUtil.getHourByTimestampLong(StringUtil.getStringToDateTimeNoT(data.getStartTime())) + "-" + StringUtil.getHourByTimestampLong(StringUtil.getStringToDateTimeNoT(data.getEndTime())));
        tvMeetingCompany.setText(data.getCompanyName());
        ivMeetingTime.setVisibility(View.VISIBLE);
        ivMeetingCompany.setVisibility(View.GONE);
        tvMeetingTime.setVisibility(View.VISIBLE);
        tvMeetingCompany.setVisibility(View.GONE);
        tvMeetingStatus.setText(tips);
        clRightCenter.setBackgroundColor(getResources().getColor(R.color.used));
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    mSmbdLed.onYellow(true);
                } catch (Exception e) {

                }
            }
        }).start();
    }

    @SuppressLint("SimpleDateFormat")
    private void initTimeData() {

        long time = System.currentTimeMillis();
        Date date = new Date(time);
        format = new SimpleDateFormat("EEEE");
        tvWeekDay.setText(format.format(date));
        format = new SimpleDateFormat("yyyy年MM月dd日");
        tvDate.setText(format.format(date));

    }

    private void initRecycler() {

        mAdapter = new IndexMeetingListAdapter(getContext());
        LinearLayoutManager manager = new LinearLayoutManager(getContext());

        rlvMeetingList.setLayoutManager(manager);
        rlvMeetingList.setAdapter(mAdapter);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onHeartBeat(HomeHeartBeatEvent event) {
        if (event != null && event.getData() != null) {

            initData();
            initTimeData();

        }
    }

    @Override
    public void onStart() {
        super.onStart();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
